import com.cinsea.common.Env;
import com.cinsea.common.ExtAction;
import com.cinsea.common.OnLineMonitor;
import com.cinsea.hrm.model.Usersetting;
import com.cinsea.hrm.service.UsersettingService;
import com.cinsea.log.service.LogService;
import com.cinsea.security.LoginUser;
import com.cinsea.security.model.User;
import com.cinsea.security.service.UserService;
import com.cinsea.util.DateUtil;
import com.cinsea.util.StringUtil;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.ProviderManager;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.ui.savedrequest.SavedRequest;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.util.PortResolverImpl;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class LoginAction extends ExtAction {
    public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String action = StringUtil.null2String(request.getParameter("action"));

        if (action.equals("fromoa")) {
            UserService userService = Env.getBean("userService");
            String username = "ssoerror";
            try {
                String appId = "CBPM_SPC";
                String tokenId = "";
                Cookie[] cookies = request.getCookies();
                //以下方法是从cookies里面获取里面获取iPlanetDirectoryPro的值 是加密字符串 tokenId=iPlanetDirectoryPro
                if (cookies != null) {
                    String cookie_name = "";
                    String cookie_value = "";
                    for (int i = 0; i < cookies.length; i++) {
                        cookie_name = cookies[i].getName();
                        cookie_value = cookies[i].getValue();
                        System.out.println(" cookie_name=" + cookie_name + "  cookie_value=" + cookie_value);
                        if (cookie_name != null && cookie_name.equals("iPlanetDirectoryPro")) {
                            tokenId = cookie_value;
                            break;
                        }
                    }
                }
                //以下方法是调用validate接口 进行验证  验证成功和失败分别返回字符串
                username = validateSSLoing(tokenId, appId);
            } catch (Exception e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            if (username.equals("ssoerror")) {
                response.sendRedirect("/main/login.jsp");
                return;
            }
            User sysuser = userService.getBy("username", username);
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(sysuser.getUsername(), sysuser.getPasswd());
            ProviderManager _providerManager = (ProviderManager) Env.getBean("switchAuthenticationManager");
            Authentication at = _providerManager.doAuthentication(token);
            if (at != null) {
                Object principal = at.getPrincipal();
                if (principal != null) {
                    if (UserDetails.class.isInstance(principal)) {
                        LoginUser vu = (LoginUser) principal;
                        GrantedAuthority[] gas = vu.getAuthorities();
                        vu.setSessionid(request.getSession(true).getId());
                        vu.setRemoteIpAddress(request.getRemoteAddr());
                        SecurityContextHolder.getContext().setAuthentication(at);
                        request.getSession().setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());
                        request.getSession().setAttribute("SPRING_SECURITY_LAST_USERNAME", username);
                        request.getSession().setAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY", new SavedRequest(request, new PortResolverImpl()));

                        LoginUser loginUser = Env.getRemoteUser();
                        UsersettingService usersettingService = (UsersettingService) Env.getBean("usersettingService");
                        Usersetting usersetting = (Usersetting) request.getSession().getAttribute("usersetting");
                        String style = "";
                        if (usersetting == null) {
                            List listpersonalset = usersettingService.findPersonalset(loginUser.getCurrentuserid());

                            if (listpersonalset.size() > 0) {
                                usersetting = (Usersetting) listpersonalset.get(0);
                                String language = usersetting.getLang();
                                loginUser.setLanguage(language);
                                request.getSession().setAttribute("usersetting", usersetting);
                            } else {
                                Locale locale = request.getLocale();
                                String languge = locale.toString();
                                loginUser.setLanguage(languge);
                            }
                        } else {
                            String language = usersetting.getLang();
                            loginUser.setLanguage(language);
                        }
                        request.getSession(true).setAttribute("loginUsermoniter", new OnLineMonitor("" + sysuser.getObjid()));
                        createlog(request, sysuser.getId());
                        request.getRequestDispatcher("/main/main.jsp").forward(request, response);
                        return;
                    }
                }
            }
            response.sendRedirect("/main/login.jsp");
        } else {
            response.sendRedirect("/main/login.jsp");
        }
    }

    private String validateSSLoing(String tokenId, String appId) {

        String ssoTokenId = "";

        if (tokenId != null) ssoTokenId = java.net.URLDecoder.decode(tokenId).replace(" ", "+");

        Integer detail = 1;
        ;
        //					 总公司，技术中心和下级企业不同
        String endPoint = "http://portal.shzb.cbpm/eeip_iam/services/validate";
        String operation = "validate";                     //调用方法名称
        String xml = "";
        Service service = new Service();
        try {
            /*
            // 利用cxf对ssoTokenId进行检验，返回字符串xml  ssoTokenId是封装在cookies里面
            JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();
            Client client = clientFactory.createClient(endPoint + "?wsdl");
            Object[] res = client.invoke(operation, ssoTokenId, appId, detail);
            xml = res[0].toString();*/
            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(new java.net.URL(endPoint));
            call.setOperationName(operation);
            // 利用axis对ssoTokenId进行检验，返回字符串xml  ssoTokenId是封装在cookies里面
            xml = (String) call .invoke(new Object[] { ssoTokenId, appId, detail });

            System.out.println("xml===" + xml);
            if (xml.contains("_returncode=0")) {                    //验证成功
                String[] returnInfo = xml.split(",");
                for (String info : returnInfo) {
                    if (info.startsWith("_cn")) {
                        String usname = info.split("=")[1];
                        return usname;
                    }
                }
            } else if (xml.contains("_returncode=1")) {            //ssoTokenId不正确
                System.out.println("ssoTokenId认证失败！");

                //return "error";
            } else if (xml.contains("_returncode=2")) {              //appId不正确  eg.CBPM_SPC
                System.out.println("应用系统Id不正确!");
                //return "error";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "ssoerror";
    }

    private void createlog(HttpServletRequest request, String sysid) {
        com.cinsea.log.model.Log log = new com.cinsea.log.model.Log();
        UserService userService = (UserService) Env.getBean("userService");
        User sysuser2 = userService.get(sysid);
        log.setObjid(sysuser2.getObjid());
        log.setObjname(sysuser2.getUsername());
        log.setSubmitor(sysuser2.getObjid());
        log.setLogtype("81");
        log.setLogdesc("用户登陆！");
        log.setSubmitip(request.getRemoteAddr());
        log.setSubmitdate(DateUtil.getCurrentDate());
        log.setSubmittime(DateUtil.getCurrentTime());
        LogService logService = (LogService) Env.getBean("logService");
        logService.createLog(log);
    }


}
